#include "node.h"

List list_init()
{
    List list;
    list.head = NULL;
    list.tail = NULL;
    list.size = 0;
    return list;
}

void node_add(List* plist, int number)
{
    Node* p = (Node*)malloc(sizeof(Node));
    p->data = number;
    p->next = NULL; 
    //find last node
    if (plist->head == NULL){
        plist->head = p;
        plist->tail = p;
    }else {
        plist->tail->next = p;
        plist->tail = p;
    }
    plist->size++;;
}

void node_print(List list)
{
    Node* p = NULL;
    for (p = list.head; p; p = p->next) {
        printf("%d\t", p->data);
    }
    printf("\n");
}

void node_delete(List* plist, int number)
{
    Node* q = NULL;//记录索引节点的上一个节点
    Node* p = plist->head;
    for (; p; q = p, p = p->next) {
        if (p->data == number) {
            if (q) {
                q->next = p->next;
            } else {
                plist->head = p->next;
            }
            free(p);
            plist->size--;
            break;
        }
    }
}

void node_free(List* plist)
{
    Node* p = plist->head;
    Node* q = p->next;
    for (; p; p = q, q = q->next) {
        printf("free %d\n", p->data);
        free(p);
    }
    // plist->head = NULL;
    // plist->tail = NULL;
    // plist->size = 0;
}